package online.zhangwenzhe.common.validation.extend;

import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class IDCardNumberValidator implements ConstraintValidator<IDCardNumber, String> {
    @Override
    public void initialize(IDCardNumber constraintAnnotation) {

    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isEmpty(s)) {
            return false;
        }

        if (s.length() != 18) {
            return false;
        }

        if (getValidateCode(s) != s.toUpperCase().charAt(17)) {
            return false;
        }
        return true;
    }

    /**
     * 十七位数字本体码权重
     */
    int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    /**
     * mod11,对应校验码字符值
     */
    char[] validate = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

    public char getValidateCode(String id17) {
        int sum = 0;
        int mode = 0;
        for (int i = 0; i < 17; i++) {
            //sum = sum + Integer.parseInt(String.valueOf(id17.charAt(i))) * weight[i];
            sum = sum + (id17.charAt(i) - 48) * weight[i];
        }
        mode = sum % 11;
        return validate[mode];
    }
}
